package com.tdu.spider.biz.service.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.tdu.spider.dao.UserRepository;
import com.tdu.spider.model.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    
    public List<UserDO> findByType(String type) {
        return userRepository.findByType(type);
    }

    
    public UserDO findByUserId(String userId) {
        return userRepository.findByUserId(userId);
    }

    @Autowired
    private UserRepository userRepository;

    private static LoadingCache<String,UserDO> userDOLoadingCache=null;

    @PostConstruct
    public void init(){
        userDOLoadingCache= CacheBuilder.newBuilder().expireAfterAccess(12, TimeUnit.HOURS)
            .build(new CacheLoader<String, UserDO>() {
                
                public UserDO load(String key) throws Exception {
                    return userRepository.findById(key).get();
                }
            });
    }

    
    public UserDO get(String userId) {
        return userDOLoadingCache.getUnchecked(userId);
    }
    
    public boolean remove(String userId) {
        userRepository.deleteById(userId);
        return true;
    }

    
    public boolean removeAll() {
        userRepository.deleteAll();
        return true;
    }

    
    public void put(UserDO userDO) {
        userRepository.save(userDO);
    }
}
